package com.github.boluo1230.wechat.dao.impl;

import com.github.boluo1230.wechat.base.config.MongoUtil;
import com.github.boluo1230.wechat.dao.MpAppDao;
import com.github.boluo1230.wechat.entity.MpApp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;


/**
 * @author Code Farmer
 * @date 2019/10/14 11:17
 */
@Repository
public class MpAppDaoImpl implements MpAppDao {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private MongoUtil mongoUtil;

    public MpApp getMyAppByAppId(String appId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("appId").is(appId));
        return mongoTemplate.findOne(query, MpApp.class);
    }

    @Override
    public MpApp insert(MpApp mpApp) {
        return mongoTemplate.insert(mpApp);
    }

    @Override
    public List<MpApp> getAll() {
        Query query = new Query();
        query.with(new Sort(Sort.Direction.DESC, "createDate"));
        return mongoTemplate.find(query, MpApp.class);
    }

    @Override
    public long upsert(MpApp mpApp) {
        Query query = new Query();
        query.addCriteria(Criteria.where("appId").is(mpApp.getAppId()));
        return mongoUtil.upsertOne(mpApp, query, MpApp.class);
    }

}
